import cv2
import numpy as np

def is_clear(image):
    """
    判断图像是否清晰，通过计算拉普拉斯方差来评估
    :param image: 输入的图像
    :return: 若清晰返回 True，否则返回 False
    """
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    variance = cv2.Laplacian(gray, cv2.CV_64F).var()
    # 可根据实际情况调整清晰度阈值
    clarity_threshold = 100
    return variance > clarity_threshold


def is_good_brightness(image):
    """
    判断图像亮度是否合适，通过计算图像的平均亮度来评估
    :param image: 输入的图像
    :return: 若亮度合适返回 True，否则返回 False
    """
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    _, _, v = cv2.split(hsv)
    average_brightness = np.mean(v)
    # 可根据实际情况调整亮度阈值范围
    min_brightness = 150
    max_brightness = 250
    return min_brightness <= average_brightness <= max_brightness


def is_good_contrast(image):
    """
    判断图像对比度是否合适，通过计算图像灰度直方图的标准差来评估
    :param image: 输入的图像
    :return: 若对比度合适返回 True，否则返回 False
    """
   # 将图像转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 计算灰度值的均值
    mean = np.mean(gray)
    # 计算每个像素值与均值的差值的平方
    squared_diff = np.power(gray - mean, 2)
    # 计算方差
    variance = np.mean(squared_diff)
    # 计算标准差，即对比度
    contrast = np.sqrt(variance)
    # 可根据实际情况调整对比度阈值范围
    min_contrast = 20
    max_contrast = 150
    return min_contrast <= contrast <= max_contrast


def is_well_aligned(image):
    """
    判断图像是否倾斜程度较小，通过霍夫变换检测直线并计算倾斜角度来评估
    :param image: 输入的图像
    :return: 若倾斜程度小返回 True，否则返回 False
    """
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10)
    if lines is not None:
        angles = []
        for line in lines:
            x1, y1, x2, y2 = line[0]
            angle = np.arctan2(y2 - y1, x2 - x1) * 180.0 / np.pi
            angles.append(angle)
        average_angle = np.median(angles)
        # 可根据实际情况调整倾斜角度阈值
        angle_threshold = 7
        return abs(average_angle) < angle_threshold
    return True


def is_suitable_for_ocr(image):
    """
    综合判断图像是否适合进行 OCR
    :param image: 输入的图像
    :return: 若适合返回 True，否则返回 False
    """
    return (is_clear(image) and
            is_good_brightness(image) and
            is_good_contrast(image) and
            is_well_aligned(image))